package com.xy6.jvm.fork;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 计算一组数的和，将计算结果保存起来
 * 
 * <pre>
 * 假设List<List<Integer>> groups，保存各组数据 
 * 1 遍历groups，计算每个分组的和，保存；
 * 2 创建n个线程，将groups分为若干组，分配给n个线程执行；
 * 3 使用fork/join框架，在fork中计算一组数的和，在join中批量将和保存起来；
 * </pre>
 * 
 * @author frank
 * @since 2018-01-01
 */
public class SumMain {

	public static void main(String[] args) throws IOException {
		List<List<Integer>> nums = makeData();
		handleMultiThread(nums);
		System.out.println(Double.valueOf(Math.ceil(10 * 1.0 / 4)).intValue());
		System.in.read();
	}

	private static List<List<Integer>> makeData() {
		int size = 1000000;
		Random r = new Random();
		List<List<Integer>> groups = new ArrayList<>(10);
		List<Integer> group;
		for (int i = 0; i < 10; i++) {
			group = new ArrayList<>(size);
			for (int j = 0; j < size; j++) {
				group.add(r.nextInt(15));
			}
			groups.add(group);
		}
		return groups;
	}

	@SuppressWarnings("unused")
	private static void handleSeq(List<List<Integer>> nums) {
		SumAbstractService sum = new SumSequence();
		sum.sum(nums);
	}

	@SuppressWarnings("unused")
	private static void handleMultiThread(List<List<Integer>> nums) {
		SumAbstractService sum = new SumMultiThread();
		sum.sum(nums);
	}

}
